<template>
  <view class="draft">
    <view
      v-for="(item, index) in myVoteAcitivity"
      :key="index"
      class="vote-item"
    >
      <view class="vote-item-header">
        <view class="vote-time">
          {{ formatDate(item.startTime) }} 至 {{ formatDate(item.endTime) }}
        </view>
      </view>
      <view class="vote-item-body">
        <image :src="getOneFromCover(item.cover)" class="vote-image"></image>
        <view class="vote-info">
          <view class="vote-title">{{ item.tittle }}</view>
          <view class="vote-description">{{ item.intro }}</view>
          <view class="vote-btn">
            <button size="mini" type="primary" @tap="openEditDialog(item)">
              编辑
            </button>
            <button size="mini" type="warn" @tap="openDeleteDialog(item)">
              删除
            </button>
            <button size="mini" type="success" @tap="publishVote(item)">
              发布
            </button>
          </view>
        </view>
      </view>
    </view>
    <view class="loading-text">没有更多数据~</view>
    <!-- 普通弹窗 -->
    <uni-popup ref="eidtPopup" background-color="#fff" type="bottom">
      <view class="popup-container">
        <uni-forms ref="voteRef" :model="voteForm" :rules="voteRules">
          <uni-forms-item name="images">
            <uni-file-picker
              limit="6"
              title="最多选择6张图片"
              fileMediatype="image"
              @select="voteImageSelect"
              @delete="voteImageDelete"
              v-model="voteForm.images"
            ></uni-file-picker>
          </uni-forms-item>
          <uni-forms-item label="投票标题:" name="tittle" label-width="85">
            <uni-easyinput
              type="text"
              v-model="voteForm.tittle"
              placeholder="请输入投票标题"
            ></uni-easyinput>
          </uni-forms-item>
          <uni-forms-item label="投票内容:" name="intro" label-width="85">
            <uni-easyinput
              type="textarea"
              v-model="voteForm.intro"
              placeholder="请输入投票内容"
            ></uni-easyinput>
          </uni-forms-item>
          <uni-forms-item label="投票类型:" name="genre" label-width="85">
            <uni-data-select
              v-model="voteForm.genre"
              :localdata="typeRange"
              placeholder="请选择投票类型"
            ></uni-data-select>
          </uni-forms-item>
          <uni-forms-item
            label="时间范围:"
            name="datetimerange"
            label-width="85"
          >
            <uni-datetime-picker
              v-model="voteForm.datetimerange"
              type="datetimerange"
              rangeSeparator="至"
            ></uni-datetime-picker>
          </uni-forms-item>
          <view class="form-btn-container">
            <button @click="editSubmit" class="submit-btn">修改</button>
          </view>
        </uni-forms>
      </view>
    </uni-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import {
  PublishState,
  voteListResponseType,
  editVoteParamsType,
  imageType,
} from "@/types/vote";
import { getMyVoteListAPI, putVoteAPI, deleteVoteAPI } from "@/api/vote";
import { onLoad } from "@dcloudio/uni-app";
import { formatDate, strToTimestamp } from "@/utils/time";
import { getOneFromCover, handleCoverToImageList } from "@/utils/vote";
import { uploadFileAPI } from "@/api/file";

onLoad(async () => {
  await getMyVoteList();
});

//发布投票
const publishVote = async (item: any) => {
  // 设置投票状态为发布状态
  item.state = PublishState.pending; //先审核

  // 更新投票活动
  try {
    await putVoteAPI(item);
    uni.showToast({
      title: "发布成功",
      icon: "success",
      duration: 1000,
    });
    // 重新获取投票列表
    getMyVoteList();
  } catch (error) {
    uni.showToast({
      title: "发布失败",
      icon: "none",
      duration: 1000,
    });
    console.error("发布失败：", error);
  }
};
const eidtPopup = ref<UniHelper.UniPopupInstance>();

//类型选项
const typeRange = [
  { text: "生活", value: "life" },
  { text: "教育", value: "education" },
  { text: "科技", value: "tech" },
  { text: "互联网", value: "internet" },
];

const voteForm: editVoteParamsType = reactive({
  id: "",
  cover: "",
  endTime: "",
  genre: "",
  intro: "",
  startTime: "",
  state: "",
  tittle: "",
  images: [],
  datetimerange: [],
});

const voteRules: UniHelper.UniFormsRules = {
  images: {
    rules: [{ required: true, errorMessage: "请上传投票活动图片" }],
  },
  tittle: {
    rules: [
      { required: true, errorMessage: "请输入投票标题" },
      { maxLength: 16, errorMessage: "投票标题不能超过16个字符" },
    ],
  },
  intro: {
    rules: [
      { required: true, errorMessage: "请输入投票内容" },
      { maxLength: 100, errorMessage: "投票内容不能超过100个字符" },
    ],
  },
  genre: {
    rules: [{ required: true, errorMessage: "请选择投票类型" }],
  },
  datetimerange: {
    rules: [{ required: true, errorMessage: "请选择时间范围" }],
  },
};

const voteRef = ref<UniHelper.UniFormsInstance>();

const myVoteAcitivity = ref<voteListResponseType[]>();

//图片是否修改
const imageIsChange = ref(false);

//获取正在编辑的投票活动
const getMyVoteList = async () => {
  const res = await getMyVoteListAPI(PublishState.editing);
  myVoteAcitivity.value = res.data;
};

//投票图片
const voteImageSelect: UniHelper.UniFilePickerOnSelect = (event) => {
  imageIsChange.value = true;
  const imageDatas = event.tempFiles.map((item: any) => {
    return { url: item.url, name: item.name };
  });
  voteForm.images.push(...imageDatas);
};

const voteImageDelete: UniHelper.UniFilePickerOnDelete = (event: any) => {
  imageIsChange.value = true;
  voteForm.images.splice(event.index, 1);
};

const openEditDialog = (item: any) => {
  imageIsChange.value = false;
  Object.assign(voteForm, item);
  voteForm.datetimerange = [item.startTime, item.endTime];
  voteForm.state = PublishState.editing;
  voteForm.images = handleCoverToImageList(voteForm.cover);
  eidtPopup.value?.open?.();
};

const editSubmit = async () => {
  await voteRef.value?.validate?.();
  if (imageIsChange.value) {
    await voteUploadFile(voteForm.images);
  }
  voteForm.startTime = strToTimestamp(voteForm.datetimerange[0]);
  voteForm.endTime = strToTimestamp(voteForm.datetimerange[1]);
  await putVoteAPI(voteForm);
  uni.showToast({
    title: "修改成功",
    icon: "success",
    duration: 1000,
  });
  getMyVoteList();
  eidtPopup.value?.close?.();
};

//上传文件
const voteUploadFile = async (imageList: imageType[]) => {
  const uploadPromises = imageList
    .map((item) => {
      if (!item.url.includes("http://campusvoting.znjz.online:9080")) {
        return uploadFileAPI(item);
      }
      return Promise.resolve(); // 返回一个 resolved 的 Promise
    })
    .filter((item) => item); // 过滤掉 undefined

  try {
    const fileUrlList = imageList
      .filter((item) =>
        item.url.includes("http://campusvoting.znjz.online:9080")
      )
      .map((item) => item.url); // 过滤掉本地图片
    const responses = await Promise.all(uploadPromises);
    const uploadedFileUrls = responses.flatMap(
      (res) => res?.data?.fileUrl || []
    ); // 处理可能为 undefined 的情况
    fileUrlList.push(...uploadedFileUrls); // 使用扩展运算符
    voteForm.cover = fileUrlList.join(","); // 使用 join 代替 toString
  } catch (error) {
    console.error("上传文件时发生错误：", error);
    // 这里可以加上用户友好的提示
  }
};

//打开删除活动弹窗
const openDeleteDialog = (item: voteListResponseType) => {
  //是否投票某选手提示弹窗
  uni.showModal({
    title: "删除提示",
    content: `是否删除活动【${item.tittle}】？`,
    success: async function (res) {
      if (res.confirm) {
        await deleteVoteAPI(item.id);
        uni.showToast({
          title: "删除成功",
          icon: "success",
          duration: 1000,
        });
        getMyVoteList();
      } else if (res.cancel) {
        console.log("用户点击取消");
      }
    },
  });
};
</script>

<style scoped lang="scss">
.draft {
  display: flex;
  flex-direction: column;
  padding: 20rpx;

  .category {
    display: flex;
    justify-content: space-around;
    padding: 4rpx 36rpx;
    .category-item {
      padding: 12rpx 36rpx;
      font-size: 28rpx;
      position: relative;
    }
    .category-item-active {
      color: #333;
      font-weight: bold;

      &::after {
        content: "";
        position: absolute;
        left: 0;
        top: 100%;
        margin-left: calc(50% - 22rpx);
        width: 44rpx;
        height: 6rpx;
        background-color: #00fffb;
        border-radius: 4rpx;
      }
    }
  }

  .vote-item {
    display: flex;
    flex-direction: column;
    margin-bottom: 20rpx;
    padding: 20rpx;
    border-radius: 12rpx;
    background-color: #fff;
    box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
    border: 1px solid #ebeef5;
    .vote-item-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10rpx;
      .vote-time {
        font-size: 24rpx;
        color: #333;
      }
      .vote-status {
        font-size: 24rpx;
        color: #333;
      }
    }
    .vote-item-body {
      display: flex;
      align-items: center;
      .vote-image {
        width: 200rpx;
        height: 200rpx;
      }
      .vote-info {
        margin-left: 20rpx;
        flex-grow: 1;
        .vote-title {
          font-size: 30rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 10rpx;
        }
        .vote-description {
          font-size: 28rpx;
          color: #666;
          line-height: 1.5;
          margin-bottom: 10rpx;
          // 单行文本省略
          text-overflow: ellipsis;
          overflow: hidden;
          word-break: break-all;
          white-space: nowrap;
        }
        .vote-btn {
          display: flex;
          justify-content: flex-end;
          margin-top: 20rpx;
        }
      }
    }
  }
}

.popup-container {
  padding: 40rpx;
  .form-btn-container {
    display: flex;
    justify-content: space-between;

    .submit-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 500rpx;
      background-color: #2979ff;
      height: 80rpx;
      font-size: 28rpx;
      border-radius: 8rpx;
      color: #fff;
    }
  }
}

.loading-text {
  text-align: center;
  font-size: 28rpx;
  color: #666;
  padding: 20rpx 0;
}
</style>
